package com.shawn.baseappbygroovydsl.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.core.view.isVisible
import androidx.viewbinding.ViewBinding
import com.choryan.quan.videowzproject.extension.ExtensionView.hide
import com.choryan.quan.videowzproject.extension.ExtensionView.show
import com.shawn.baseappbygroovydsl.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author Secret
 * @since 2023/10/11
 */
abstract class DialogBase<T:ViewBinding>(private val context: Context) : Dialog(context, R.style.Dialog_Base) {

    protected val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    private var vCloseHolder:View? = null
    private var ivClose:View? = null
    protected lateinit var viewBinding:T
    var iDialogActionListener:IDialogActionListener? = null
//    private var nativeAdContainer:ViewGroup? = null



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = createViewBinding()
        val rootView = viewBinding.root
//        nativeAdContainer = rootView.findViewById(R.id.fl_native_ad_container)
        vCloseHolder = rootView.findViewById(R.id.v_common_close)
        ivClose = rootView.findViewById(R.id.iv_common_close)
        vCloseHolder?.setOnClickListener {
            if(ivClose?.isVisible == false){
                return@setOnClickListener
            }
            dismiss()
            postClickDismissBtn()
        }
        setContentView(rootView)
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setOnDismissListener {
            coroutineScope.coroutineContext.cancelChildren()
//            nativeAdContainer?.removeAllViews()
            postDismiss()
            iDialogActionListener?.onDialogActionListener(DIALOG_DISMISS)
        }
        immersiveFullScreen()
        postCreate()
        if(observeKeyCodeBack()){
            setOnKeyListener { _, keyCode, keyEvent ->
                if(keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == KeyEvent.ACTION_UP){
                    onKeyCodeBack()
                    return@setOnKeyListener true
                }
                false
            }
        }
    }

    protected open fun observeKeyCodeBack() = false

    protected open fun onKeyCodeBack(){
        dismiss()
    }

    override fun show() {
        super.show()
        window?.setLayout(windowWidth(), windowHeight())
        if(delayShowClose()){
            ivClose?.hide()
            ivClose?.let {
                it.hide()
                coroutineScope.launch {
                    delay(delayShowCloseTime())
                    it.show()
                }
            }
        }else{
            ivClose?.show()
        }
//        nativeAdContainer?.let {
//            UtilEvent.trackEvent("native_trigger","scenes",nativeAdScene())
//            UtilEvent.trackEvent("native_location","scenes",nativeAdScene())
//            AdLocalManager.showDialogNative(context as Activity,nativeAdScene(),it)
//        }

        postShow()
        iDialogActionListener?.onDialogActionListener(DIALOG_SHOW)
    }

    open fun nativeAdScene() = ""

    private fun immersiveFullScreen(){
        window?.let { win ->
            win.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE;//获取视口全屏大小
            win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //这个flag表示window负责绘制状态栏的背景当设置了这个flag,系统状态栏会变透明,同时这个相应的区域会被填满 getStatusBarColor() and getNavigationBarColor()的颜色
            win.statusBarColor = Color.TRANSPARENT//设置bar为透明色
            val layoutParams = win.attributes;//获取dialog布局的参数
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;//宽全屏
            layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;//高全屏
            win.navigationBarColor = Color.TRANSPARENT//设置导航栏颜色
            win.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL)//内容扩展到导航栏
            if (Build.VERSION.SDK_INT >= 28) {
                layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            }
            val dimAmount = dimAmount()
            if(dimAmount != -1f){
                layoutParams.dimAmount = dimAmount
            }
            win.attributes = layoutParams
//            win.setBackgroundDrawable(null)
            win.setWindowAnimations(windowAnimationRes())
        }
    }

    abstract fun createViewBinding(): T

    protected open fun dimAmount() = -1f

    protected open fun windowWidth() = WindowManager.LayoutParams.MATCH_PARENT

    protected open fun windowHeight() = WindowManager.LayoutParams.MATCH_PARENT

    protected open fun postShow() {}

    protected open fun postDismiss() {}

    protected open fun postCreate(){}
    
    protected open fun postClickDismissBtn(){}
    
    protected open fun delayShowClose():Boolean = true

    protected open fun delayShowCloseTime() = 1500L

    protected open fun windowAnimationRes() = R.style.Dialog_Animation_Base

    interface IDialogActionListener{

        fun onDialogActionListener(position:String,params:Any? = null)

    }
    companion object{
        const val DIALOG_SHOW:String= "dialog_show"
        const val DIALOG_DISMISS:String= "dialog_dismiss"
    }

}